package kr.couponplay.android.domain.deal;

import java.util.ArrayList;
import java.util.List;

import kr.couponplay.android.ApiUrl;
import kr.couponplay.android.AppContext;
import kr.couponplay.android.Constants;
import kr.couponplay.android.domain.BaseDao;
import kr.couponplay.android.support.HttpUtils;
import kr.couponplay.android.support.StringUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class QnaDao extends BaseDao {
	public List<QnaBox> selectList(int dealId, String providerCode, String metaId) {
		try {
			StringBuffer queryParams = new StringBuffer();
			queryParams.append("?sid=" + StringUtils.trimToEmpty(AppContext.getSid(getApplicationContext())));
			queryParams.append("&dealId=" + dealId);
			queryParams.append("&providerCode=" + providerCode);
			queryParams.append("&metaId=" + metaId);
			String url = ApiUrl.dealQnaUrl + queryParams;
			
			String data = HttpUtils.executeToStr(url);
			JSONObject qanListObj = new JSONObject(data).getJSONObject("qnaList");
			JSONArray qnaBoxJsonArray = qanListObj.getJSONArray("qnaBoxList");
			
			List<QnaBox> qnaBoxList = new ArrayList<QnaBox>();
			for (int i = 0; i < qnaBoxJsonArray.length(); i++) {
				JSONObject qnaBoxObj = qnaBoxJsonArray.getJSONObject(i);
				JSONObject questionObj = qnaBoxObj.getJSONObject("question");
				JSONArray answerArray = qnaBoxObj.getJSONArray("answers");
				
				Qna question = new Qna();
				question.setUserName(questionObj.getString("userName"));
				question.setRegisteDate(questionObj.getString("registeDate"));
				question.setContent(questionObj.getString("content"));
				
				List<Qna> answers = new ArrayList<Qna>();
				for (int j=0; j < answerArray.length(); j++) {
					Qna answer = new Qna();
					answer.setUserName(answerArray.getJSONObject(j).getString("userName"));
					answer.setRegisteDate(answerArray.getJSONObject(j).getString("registeDate"));
					answer.setContent(answerArray.getJSONObject(j).getString("content"));
					answers.add(answer);
				}
				
				qnaBoxList.add(new QnaBox(question, answers));
			}
			return qnaBoxList;
		} catch (JSONException e) {
			Log.e(Constants.TAG, e.getMessage(), e);
			throw new IllegalStateException(e.getMessage(), e);
		} catch (Exception e2) {
			throw new IllegalStateException(e2.getMessage(), e2);
		}
	}
}
